<?php
/**
 * Created by b17
 * 2/16/12 7:33 PM
 */

namespace Managers\Result;

class Base
{
    /**
     * @var \Managers\Searchers\Base
     */
    protected $searcher;
    /**
     * @var \Managers\MatchesManager
     */
    protected $manager;

    /**
     * @var \Managers\Decorators\Decorator|null
     */
    protected $decorator;

    protected $total = 0;

    protected $results = false;

    public function __construct(\Managers\Searchers\Base $searcher, \Managers\MatchesManager $manager)
    {
        $this->searcher = $searcher;
        $this->manager = $manager;
    }

    protected function doSearch()
    {
        $sphinxResults = $this->searcher->getResult();
        $matches = array();
        foreach ($sphinxResults as $result) {
            if (isset($result['matches'])) {
                $matches[] = $result['matches'];
            }
        }
        $matches = $this->doFilter($matches);
        if (!count($matches)) {
            throw new \LogicException('Nothing found.');
        }
        $this->results = $this->doLoad($matches);
        $this->doCountTotal($sphinxResults);
    }

    protected function doCountTotal($results)
    {
        $total = 0;
        foreach ($results as $result) {
            $total += $result['total_found'];
        }
        $this->total = $total;
    }

    protected function doFilter($matches)
    {
        $result = array();
        foreach ($matches as $match) {
            $result = array_merge($result, $match);
        }
        return $result;
    }

    protected function doLoad($matches)
    {
        return $this->manager->getByMatches($matches);
    }

    public function getResult()
    {
        if ($this->results === false) {
            $this->doSearch();
        }
        return $this->decorator ? $this->decorator->decorate($this->results) : $this->results;
    }

    public function getTotalResults()
    {
        if ($this->results === false) {
            $this->doSearch();
        }

        return $this->total;
    }

    /**
     * @param \Managers\Decorators\Decorator $decorator
     */
    public function setDecorator(\Managers\Decorators\Decorator $decorator)
    {
        $this->decorator = $decorator;
    }


}
